package wiki.kaizen.cloud.plugin.spring;

import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.Map;

public class SimpleTuber<T> {
    private Map<String,Object> map;
    private T data = null;
    private SimpleTuber(Map<String, Object> map) {
        this.map = map;
    }
    private SimpleTuber() {
        this.map = new HashMap<>();
    }
    private SimpleTuber(int size) {
        this.map = new HashMap<>(size);
    }
    private SimpleTuber(T data){
        this.data = data;
    }

    public <T> SimpleTuber<T> msg(String msg){
        return this.put("msg",msg);
    }

    public static SimpleTuber<Void> OK(){
        return null;
    }

    public static<T> SimpleTuber<T> start(){
        return new SimpleTuber<>();
    }

    public static<T> SimpleTuber<T> start(int size){
        return  new SimpleTuber<>(size);
    }

    public static<T> SimpleTuber<T> data(T data){
        return new SimpleTuber<>(data);
    }

    public static<T> SimpleTuber<T> start(Map<String,Object> map){
        return new SimpleTuber<>(map);
    }

	/**
	 * 调用此方法 有事务 则事务回滚
	 */
    public static<T> SimpleTuber<T> error(int size){
		SimpleTuber.rollback();
        return SimpleTuber
            .start(size+1)
            .put("code",HttpStatusCode.WRONG_PARAMETER);
    }
	/**
	 * 调用此方法 有事务 则事务回滚
	 */
    public static<T> SimpleTuber<T> error(String msg){
        return SimpleTuber.error(HttpStatusCode.WRONG_PARAMETER,msg);
    }
	/**
	 * 调用此方法 有事务 则事务回滚
	 */
    public static<T> SimpleTuber<T> error(int code,String msg){
		return SimpleTuber.error(code,msg,true);
    }
	public static<T> SimpleTuber<T> error(int code,String msg,boolean rollback){
    	if (rollback){
			SimpleTuber.rollback();
		}
		return SimpleTuber.error(2)
			.put("code",code)
			.put("msg",msg);
	}
	/**
	 * 调用此方法 有事务 则事务回滚
	 */
    public  static<T> SimpleTuber<T> error(String format,Object... args){
        return SimpleTuber.error(HttpStatusCode.WRONG_PARAMETER,format,args);
    }
	/**
	 * 调用此方法 有事务 则事务回滚
	 */
    public  static<T> SimpleTuber<T> error(int code,String format,Object... args){
        return error(code,String.format(format, args));
    }

    @SuppressWarnings("unchecked")
    public <T> SimpleTuber<T> put(String key, Object value){
        this.map.put(key,value);
        return (SimpleTuber<T>) this;
    }
    public Map<String, Object> get() {
        return  this.map;
    }

    public T getData() {
        return data;
    }

    public static void rollback(){
    	try{
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}catch (Exception ignore){}
    }
}
